Variable

Variables are simply a storage location, In Scala we can define variable by its data type and name, compiler allocates reserved location to the  data type of the corresponding variable.

Syntax
val or val variable_name: variable_datatype = value;

In Scala there are two types of variable.
  • Mutable Variables
  • Immutable Variables
val or val variable_name: variable_datatype = value;
Mutable Variables
Mutable variables are defined with the var Keyword. Here, myVar is declared using the keyword var. It is a variable that can change value and this is called mutable variable.The first letter of data type should be in capital letter because in Scala data type is teared as objects.

scala>  var myVar : String = "Foo"
myVar: String = Foo

scala> myVal="Hi"
myVal: String = Hi            
// No Error: reassignment to var 

Immutable Vriables
Variables which do not allow you to change a value after the declaration of a variable. Immutable variables are defined by using the val keyword.The first letter of data type should be in capital letter because in the Scala data type is treated as objects. Here, myVal is declared using the keyword val. This means that it is a variable that cannot be changed and this is called immutable variable. Following is the syntax to define a variable using val keyword −

scala> val myVal : String = "Foo"
myVal: String = Foo

scala> myVal="Hi"
<console>:8: error: reassignment to val
       myVal="Hi"
            ^

Rules for naming variable in Scala
  • Variable name should be in lower case.
  • Variable name can contain letter, digit and two special characters(Underscore(_) and Dollar($) sign)
  • Variable name must not contain the keyword or reserved word.
  • Starting letter of the variable name should be an alphabet.
  • White space is not allowed in variable name.
Variable Data Types
The type of a variable is specified after the variable name and before equals sign. You can define any type of Scala variable by mentioning its data type as follows −

val or var VariableName : DataType = [Initial Value]
val myVar : Any ="Hello"

Variable Type Inference

When you assign an initial value to a variable, the Scala compiler can figure out the type of the variable based on the value assigned to it. This is called variable type inference. Therefore, you could write these variable declarations like this −

var myVar = 10;
val myVal = "Hello, Scala!";

Here, by default, myVar will be Int type and myVal will become String type variable.

Multiple Deceleration and  Assignments
Multiple deceleration can be possible in scala using the var keyword with variable name separated by commas  and the "=" sign with the value variable.

val (x: Int, y: String,z: Int) = (40,"Hi",5)
object Demo {
def main(args: Array[String]) {
val (x: Int, y: String,z: Int) = (40,"Hi",5)
println(x)
println(y)
println(z)
}
}
The multiple assignments can be possible in Scala in one line by using 'val' keyword with variable name separated by commas and the "=" sign with the value for the variable.

val a, b, c = 1;
object Demo {
def main(args: Array[String]) {
val a, b, c = 1;
println(a)
println(b)
println(c)
}
}

The following is an example program that explains the process of variable declaration in Scala. This program declares four variables — two variables are defined with type declaration and remaining two are without type declaration.

object demo {
def main(args: Array[String]) {
var myVar :Int = 10;
val myVal :String = "Hello Scala with datatype declaration.";
var myVar1 = 20;
val myVal1 = "Hello Scala new without datatype declaration.";
println(myVar);
println(myVal);
println(myVar1);
println(myVal1);
}
}
10
Hello Scala with datatype declaration.
20
Hello Scala without datatype declaration.

Scope of a Variable
The scope is the visibility of the variables which have its life-time inside the specified blocks of the code. The variable can be defined in either Local or Global Scope.

There are three types of scope for variables in Scala (Source: Scala- Variables):
  • Local variables
  • Fields
  • Method Parameters
Local Variables
Local variables are mutable or immutable variables that are declared inside a method and can only be accessible inside methods but not outside it.
class Perimeter
{
def triangle()
{
var side1 = 10;
var side2 = 20;
var side3 = 30;
var total = side1+side2+side3;
print("Perimeter of the triangle is: " + total);
}
}

object demo
{
def main(args:Array[String])
{
val p1 = new Perimeter()
p1.triangle()
}
}
Fields
Those variables defined inside the class are known to be as field variables which can be of any type either mutable or immutable variables. The access modifier will be automatically public if the variable is declared inside the class but should not be defined inside any method where the variable is accessible to anywhere in the program. However, a private variable can be accessed inside the defined class but cannot be accessed outside the scope of the class or even in the object too.

class FieldExample
{
  var value1 = 10;
  private var value2 = 30;
  def operation()
  {
    println("Value of value1:"+value1)
  }
  println("Value of value2: "+value2);
}

object Demo
{
  def Main(args:Array[String])
  {
    val obj = new FieldExample()
    obj.operation()
    print(obj.value1)//Valid
    print(obj.value2)
  }
}

Method Parameters
The method parameters are the variables that accept the value when the method is being called, and the variable must be mutable, which is defined using 'val' keyword. Also, the variable can be accessed outside the method when there is a reference made to it.

You can see the simple example below to know about Method Parameters:
class Triangle
{
def calculate(height: Int, width: Int)
{
var result = 0.5*(height+width);
println("Area of triangle is: " + result);
}
}

object Demo
{
def main(args:Array[String])
{
val a = new Triangle()
a.calculate(4,5);
}
}

No comments:

Post a Comment